package cn.hh.wechatkit.component;

import cn.hh.wechatkit.api.user.WxAPI_UnionInfo_Api;
import cn.hh.wechatkit.exception.Wx_Exception_GetTokenFailed;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidJsonParse;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidParam;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import cn.hh.wechatkit.helper.CacheHelper;
import cn.hh.wechatkit.param.WxParam;
import cn.hh.wechatkit.pojo.user.Wx_UnionInfo;
import cn.hh.wechatkit.util.WxAuthoUtil;

import java.io.IOException;

/**
 * Created this one by HMH on 2017/5/23.
 * User管理组件
 */
public class WxCom_User {

    /**
     * 通过code拉取用户信息
     *
     * @param code autho验证返回的code
     * @return Wx_UnionInfo对象
     * @throws Wx_Exception_GetTokenFailed   获取异常
     * @throws Wx_Exception_InvalidResponse  无效请求异常
     * @throws Wx_Exception_InvalidJsonParse 无效json异常
     * @throws IOException                   io异常
     */
    public Wx_UnionInfo getUnionInfoByCode(String code) throws Wx_Exception_GetTokenFailed, Wx_Exception_InvalidResponse, Wx_Exception_InvalidJsonParse, IOException {
        return WxAPI_UnionInfo_Api.getUnion_Info_By_AuthoCode(CacheHelper.getAccessToken().getAccess_token(), code);
    }

    /**
     * 通过OpenId拉取用户信息
     *
     * @param openId 需要查询用户的openId
     * @return Wx_UnionInfo对象
     * @throws Wx_Exception_GetTokenFailed   获取异常
     * @throws Wx_Exception_InvalidResponse  无效请求异常
     * @throws Wx_Exception_InvalidJsonParse 无效json异常
     * @throws IOException                   io异常
     */
    public Wx_UnionInfo getUnionInfoByOpenId(String openId) throws Wx_Exception_GetTokenFailed, Wx_Exception_InvalidResponse, Wx_Exception_InvalidJsonParse, IOException {
        return WxAPI_UnionInfo_Api.getUnion_Info_By_OpenId(CacheHelper.getAccessToken().getAccess_token(), openId);
    }

    /**
     * 获取认证URL
     *
     * @param redirectUrl 回调页面路径
     * @param scope       授权作用域（snsapi_base或snsapi_userinfo）
     * @param state       授权状态
     * @return 授权页面路径
     */
    public String getAuthoUrl(String redirectUrl, int scope, String state) throws Wx_Exception_InvalidParam {
        String scopeStr;
        if (scope == SCOPE_SNSAPI_BASE) {
            scopeStr = "snsapi_base";
        } else if (scope == SCOPE_SNSAPI_USERINFO) {
            scopeStr = "snsapi_userinfo";
        } else {
            throw new Wx_Exception_InvalidParam("scope错误，请使用静态变量赋值");
        }
        return WxAuthoUtil.getAuthoUrl(WxParam.appId, redirectUrl, scopeStr, state);
    }

    public static int SCOPE_SNSAPI_BASE = 0;
    public static int SCOPE_SNSAPI_USERINFO = 1;


}
